package org.github.manx98.jlibhac.tools.fs;

import org.github.manx98.jlibhac.common.keys.KeySet;
import org.github.manx98.jlibhac.fs.IStorage;
import org.github.manx98.jlibhac.fs.fsa.OpenMode;
import org.github.manx98.jlibhac.fssystem.PartitionFileSystem;

import java.io.IOException;

/**
 * XCI 磁盘文件
 *
 * @author Manx98
 * @version 1.0
 * @since 2022/10/3 1:26
 */
public class Xci {
    private final IStorage baseStorage;
    private final KeySet keySet;
    private final XciHeader header;
    private XciPartition rootPartition;

    public Xci(KeySet keySet, IStorage storage) throws IOException {
        this.keySet = keySet;
        this.header = new XciHeader(keySet, storage.asStorage());
        if (header.HasInitialData) {
            baseStorage = storage.slice(0x1000);
        } else {
            this.baseStorage = storage;
        }
    }

    public XciPartition openPartition(XciPartitionType type) throws IOException {
        XciPartition root = getRootPartition();
        if (type == XciPartitionType.Root) {
            return root;
        }
        IStorage iStorage = root.doOpenFile(type.getFilename(), OpenMode.Read);
        return new XciPartition(iStorage);
    }

    public XciPartition getRootPartition() throws IOException {
        if (rootPartition != null) {
            return rootPartition;
        }

        initializeRootPartition();

        return rootPartition;
    }

    private void initializeRootPartition() throws IOException {
        IStorage root = baseStorage.slice(header.rootPartitionOffset);
        this.rootPartition = new XciPartition(root);
        this.rootPartition.offset = header.rootPartitionOffset;
    }

    public XciHeader getHeader() {
        return header;
    }
}
